package top.codedance.iotp.loadblance.algorithm;

import top.codedance.iotp.loadblance.entiy.RegistyUri;

import java.util.List;

public class Auto extends Adapter {
    private static RegistyUri registyUri = null;
    @Override
    public String execute(List<RegistyUri> registyUris, Func<String> func) {
        String serverUrl = null;
        if(registyUri == null){
            serverUrl = exec(registyUris, func);
        }else{
            serverUrl = func.run(registyUri.getUrl());
            if(serverUrl == null){
                registyUri = null;
                serverUrl = exec(registyUris, func);
            }
        }
        return serverUrl;
    }

    private String exec(List<RegistyUri> registyUris, Func<String> func){
        String serverUrl = null;
        for(RegistyUri ru : registyUris){
            serverUrl = func.run(ru.getUrl());
            if(serverUrl != null){
                registyUri = ru;
                break;
            }
        }
        return serverUrl;
    }
}
